package com.graduation.project.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.graduation.project.entity.other.LoginUser;
import com.graduation.project.entity.po.User;
import com.graduation.project.mapper.system.MenuMapper;
import com.graduation.project.mapper.system.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 卑微小峰
 * @date 2022/11/16
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String userCode) throws UsernameNotFoundException {
        // 查询用户信息
        LambdaQueryWrapper<User> lambdaQueryUserWrapper = new LambdaQueryWrapper<>();
        lambdaQueryUserWrapper.eq(User::getUserCode, userCode)
                .eq(User::getUserStatus, 0);
        User user = userMapper.selectOne(lambdaQueryUserWrapper);
        if (ObjectUtil.isEmpty(user)) {
            throw new UsernameNotFoundException("用户不存在或已被禁用");
        }
        // 查询权限信息
        List<String> permissions = menuMapper.listMenuPermsByUserId(user.getId());

        // 把数据封装成UserDetails返回
        return new LoginUser(user, permissions);
    }
}
